<?php
class AclController extends AdminController {
	public function AclController(){
		parent::AdminController();
	}
	
	public function index(){
		$acl_mod = new AclModel();
		$acl_array = $acl_mod->find(array('sys'=>SYSTEM));
		$this->assign('acl_list', $acl_array);
		$this->display();
	}
	
	public function edit(){
		$acl_mod = new AclModel();
		if(IS_POST){
			self::save_acl();
		}else{
			$acl_mod = new AclModel();
			$acl_list = $acl_mod->find(array('sys'=>SYSTEM));
			$this->assign('acl_list', $acl_list);
			if(isset($_GET['ns']) && isset($_GET['acl'])){
				//编辑某个权限
				$ns = trim($_GET['ns']);
				$acl_value = intval($_GET['acl']);
//				print_r($acl_list);exit;
				if(isset($acl_list[$ns]['items'][$acl_value])){
					$cur_acl = $acl_list[$ns];
					$acl = array(
						'_id' => $cur_acl['_id'],
						'name' => $cur_acl['name'],
						'acl_value' => $acl_value,
						'acl_name' => $cur_acl['items'][$acl_value]['name'],
						'acl_desc' => $cur_acl['items'][$acl_value]['desc'],
						'namespace' => $ns,
					);
					$this->assign('acl', $acl);
				}
			}
			//获取所有的Namespaces
			$namespaces = $acl_mod->find(array('sys'=>SYSTEM), 'name');
			$ns_options = array();
			foreach($namespaces as $ns=>$n_i){
				$ns_options[$ns] = $n_i['name'];
			}
			$this->assign('namespaces', $ns_options);
			$this->display();
		}
	}

	private function save_acl(){
		$acl_mod = new AclModel();
		$namespace = trim($_POST['namespace']);
		$acl = intval($_POST['acl']);
		$name = trim($_POST['name']);
		$desc = trim($_POST['desc']);
		
		if($acl<0){
			self::ajax_error('权限值不能小于0');
		}
		if($acl>64){
			self::ajax_error('权限值不能大于64');
		}
		$acl_item = array(
			'name'=>$name,
			'desc' => $desc,
		);
		if($namespace=='0'){
			//新建模块
			$new_ns = trim($_POST['new_ns']);
			$new_desc = trim($_POST['new_desc']);
			//验证是否已经存在
			if($acl_mod->exists_attrs(array('_id'=>$new_ns,'sys'=>SYSTEM))){
				$this->error('此命名空间已经存在！');
			}
			//新增
			$acl_obj = array(
				'_id' => $new_ns,
				'name'=> $new_desc,
				'sys' => SYSTEM,
				'items' => array($acl=>$acl_item),
			);
			$acl_mod->insert($acl_obj);
			self::ajax_info('权限新建成功！');
		}else{
			//新增权限
			$acl_obj = array(
				'items.' . $acl => $acl_item,
			);
			$acl_mod->update_by_key($namespace, $acl_obj);
			self::ajax_info('权限更新成功！');
		}
	}
	
	public function del(){
		$acl = self::get_int_val('acl', -1);
		$ns = self::get_val('ns');
		
		$acl_mod = new AclModel();
		$acl_obj = $acl_mod->get_by_key($ns);
		if(empty($acl_obj)){
			self::ajax_error('要删除的权限不存在或已被删除！');
		}
		if(!isset($acl_obj['items']) || count($acl_obj['items'])<2){
			//如果权限只有1个，则直接删除整个文档
			$acl_mod->delete_by_key($ns);
		}else{
			//删除此权限
			$acl_mod->delete_column_by_key($ns, 'items.' . $acl);
		}
		self::ajax_info('权限删除成功！');
	}
}

?>